<template>
  <view class="all-orders">
    <!-- 加载状态 -->
    <uni-load-more v-if="loading" status="loading"></uni-load-more>
    
    <!-- 无订单提示 -->
    <view v-else-if="!allOrders || allOrders.length === 0" class="empty-orders">
      <text>暂无订单</text>
      <view class="action-buttons">
        <button type="primary" class="goto-shop" @tap="goToShop">去逛逛</button>
        <button type="default" class="refresh-btn" @tap="fetchAllOrders">刷新</button>
      </view>
    </view>

    <view v-else class="order-list">
      <view 
        v-for="order in allOrders" 
        :key="order._id"
        class="order-card animate__animated animate__fadeIn"
      >
        <view class="order-header">
          <text class="order-no">订单号: {{ order.order_no }}</text>
          <text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
        </view>
        
        <view class="order-content">
          <view 
            v-for="item in order.products" 
            :key="item.id"
            class="order-item"
          >
            <image 
              :src="url('sp',item.image-1,'png')" 
              mode="aspectFill"
              class="item-image"
            />
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-spec">{{ formatSpecs(item.specs) }}</text>
              <view class="item-price-qty">
                <text class="price">¥{{ item.price }}</text>
                <text class="quantity">x{{ item.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <view class="total">
            共{{ order.products.length }}件商品
            <text class="total-amount">合计: ¥{{ order.total_price }}</text>
          </view>
          <view class="actions">
            <button 
              v-if="order.status === 'pending'"
              type="default"
              @tap="cancelOrder(order)"
            >
              取消订单
            </button>
            <button 
              v-if="order.status === 'pending'"
              type="warn"
              @tap="payOrder(order)"
            >
              立即付款
            </button>
            <button 
              v-if="order.status === 'shipping'"
              type="warn"
              @tap="confirmReceived(order)"
            >
              确认收货
            </button>
            <button 
              v-if="order.status === 'review'"
              type="primary"
              @tap="goToReview(order)"
            >
              去评价
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'

const url = $url
const userStore = useUserStore()
const loading = ref(true)
const allOrders = ref([])

// 格式化规格
const formatSpecs = (specs) => {
  if (!specs) return '';
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ');
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'unpaid': '待发货',
    'shipping': '待收货',
    'review': '待评价',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'unpaid': 'status-unpaid',
    'shipping': 'status-shipping',
    'review': 'status-review',
    'completed': 'status-completed',
    'cancelled': 'status-cancelled'
  };
  return classMap[status] || '';
};

// 获取所有订单
const fetchAllOrders = async () => {
  loading.value = true;
  
  try {
    console.log('开始获取所有订单...');
    
    // 确保用户已登录
    if (!userStore.isLoggedIn || !userStore.userInfo || !userStore.userInfo.account) {
      console.error('用户未登录，无法获取订单');
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      loading.value = false;
      return;
    }
    
    // 获取所有状态的订单
    const statuses = ['pending', 'unpaid', 'shipping', 'review', 'completed', 'cancelled'];
    const orders = await Promise.all(
      statuses.map(status => userStore.getOrdersByStatus(status))
    );
    
    // 合并所有订单并按创建时间排序
    allOrders.value = orders
      .flat()
      .sort((a, b) => b.create_time - a.create_time);
    
    console.log('获取到的所有订单:', allOrders.value);
    
  } catch (error) {
    console.error('获取订单失败:', error);
    uni.showToast({
      title: error.message || '获取订单失败',
      icon: 'none'
    });
    allOrders.value = [];
  } finally {
    loading.value = false;
  }
};

// 取消订单
const cancelOrder = async (order) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const success = await userStore.updateOrderStatus(order._id, 'cancelled');
          if (success) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            // 重新获取订单列表
            fetchAllOrders();
          }
        } catch (error) {
          uni.showToast({
            title: '取消订单失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 支付订单
const payOrder = (order) => {
  uni.showModal({
    title: '支付',
    content: `确认支付¥${order.total_price.toFixed(2)}?`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const success = await userStore.updateOrderStatus(order._id, 'unpaid');
          if (success) {
            uni.showToast({
              title: '支付成功',
              icon: 'success'
            });
            // 重新获取订单列表
            fetchAllOrders();
          }
        } catch (error) {
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 确认收货
const confirmReceived = async (order) => {
  uni.showModal({
    title: '确认收货',
    content: '确认已收到商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const success = await userStore.updateOrderStatus(order._id, 'review');
          if (success) {
            uni.showToast({
              title: '已确认收货',
              icon: 'success'
            });
            // 重新获取订单列表
            fetchAllOrders();
          }
        } catch (error) {
          uni.showToast({
            title: '确认收货失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 去评价
const goToReview = (order) => {
  uni.navigateTo({
    url: `/pages/my/review?orderId=${order._id}`
  });
};

// 跳转到商城页面
const goToShop = () => {
  uni.switchTab({
    url: '/pages/shop/index'
  });
};

onMounted(async () => {
  // 检查用户是否登录
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });
    
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/other/login'
      });
    }, 2000);
    return;
  }
  
  // 加载订单数据
  await fetchAllOrders();
});
</script>

<style lang="scss" scoped>
.all-orders {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-top: 30rpx;
  width: 240rpx;
}

.goto-shop, .refresh-btn {
  font-size: 28rpx;
}

.order-card {
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.order-status {
  &.status-pending {
    color: var(--td-warning-color);
  }
  &.status-unpaid {
    color: var(--td-warning-color);
  }
  &.status-shipping {
    color: var(--td-brand-color);
  }
  &.status-review {
    color: var(--td-success-color);
  }
  &.status-completed {
    color: var(--td-success-color);
  }
  &.status-cancelled {
    color: var(--td-error-color);
  }
}

.order-item {
  display: flex;
  margin-bottom: 20rpx;
}

.item-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
}

.item-info {
  flex: 1;
  margin-left: 20rpx;
}

.item-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
}

.item-price-qty {
  display: flex;
  justify-content: space-between;
  margin-top: 10rpx;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.quantity {
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx solid #f5f5f5;
}

.total {
  font-size: 28rpx;
  color: #666;
}

.total-amount {
  color: #333;
  font-weight: bold;
  margin-left: 10rpx;
}

.actions {
  display: flex;
  gap: 20rpx;
}

.actions button {
  font-size: 26rpx;
  padding: 10rpx 30rpx;
  border-radius: 60rpx;
}
</style> 